﻿using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.IO;
using System.Text;
using Accountant.DataModel;

namespace Accountant.MySerializer
{
  public abstract class DbContext : IDisposable
  {
    private Database _database;
    public bool IsLoading { get; set; }

    public void SaveChanges()
    {
      SaveCore(Database);
#if DEBUG
      using (var dump = Database.CreateDump())
        Dump(new IndentedTextWriter(dump));
#endif
    }

    public void Load()
    {
      if (!Database.Exists)
      {
        Database.Create();
        Database.InitializeDatabase(this);
      }
      else
      {
        IsLoading = true;
        LoadCore(Database);
        IsLoading = false;
      }
    }

    public Database Database
    {
      get { return _database ?? (_database = GetDatabase()); }
      set { _database = value; }
    }

    protected abstract void LoadCore(Database db);

    public void Dispose()
    {
    }

    protected abstract void SaveCore(Database db);
    protected abstract Database GetDatabase();

    protected abstract void Dump(IndentedTextWriter writer);
    public string Dump()
    {
      var sb = new StringBuilder();
      Dump(new IndentedTextWriter(new StringWriter(sb)));
      return sb.ToString();
    }
  }
}